use serde::{Deserialize, Serialize};
use std::{fs, path::Path};

use crate::parse;

/// list.json文件数据结构
#[derive(Debug, Serialize, Deserialize)]
struct IDFile
{
    count: usize,
    maxid: u16,
    datas: Vec<IDMeta>,
}

///  生成结构的元信息结构
#[derive(Debug, Serialize, Deserialize)]
struct IDMeta
{
    pub name: String, //结构名字
    pub id: u16,      //结构在整个序列化系统里面的编号
    pub check: u16,   //结构里全部字段类型组成的crc16，用于效验是否可以对应解析
    pub file: String, //源代码文件
    pub line: usize,  //源代码行
}

/// list.json文件数据
static mut ID_FILE: IDFile = IDFile {
    count: 0,
    maxid: 0,
    datas: Vec::new(),
};

/// xxxx
pub fn generate(parse_struct: &parse::Struct, check: u16) -> u16
{
    let mut id = 0;

    let generate_file_dir = format!(
        "{}/target/ser",
        std::env::current_dir().unwrap().to_str().unwrap()
    );
    let list_file_path = format!("{}/list.josn", generate_file_dir);

    unsafe {
        if ID_FILE.count == 0
        {
            if Path::new(&list_file_path).exists()
            {
                ID_FILE = serde_json::from_slice(fs::read(&list_file_path).unwrap().as_mut_slice())
                    .unwrap();
            }
            else
            {
                fs::create_dir_all(&generate_file_dir).expect("创建/target/ser文件夹出错！");
            }
        }

        for idmd in ID_FILE.datas.iter_mut()
        {
            if idmd.name == parse_struct.struct_name
            {
                id = idmd.id;
                idmd.check = check;
                idmd.file = parse_struct.file_name.clone();
                idmd.line = parse_struct.line;
                break;
            }
        }
        if id == 0
        {
            for idmd in ID_FILE.datas.iter_mut()
            {
                if idmd.file == parse_struct.file_name
                    && idmd.check == check
                    && idmd.line == parse_struct.line
                {
                    id = idmd.id;
                    idmd.name = parse_struct.struct_name.clone();
                    break;
                }
            }
        }
        if id == 0
        {
            let mut max_id = 0;
            for idmd in &ID_FILE.datas
            {
                if idmd.id > max_id
                {
                    max_id = idmd.id;
                }
            }
            id = max_id + 1;
            ID_FILE.datas.push(IDMeta {
                name: parse_struct.struct_name.clone(),
                id: id,
                check: check,
                file: parse_struct.file_name.clone(),
                line: parse_struct.line,
            });
            ID_FILE.count = ID_FILE.datas.len();
            ID_FILE.maxid = id;
        }
        fs::write(
            Path::new(&list_file_path),
            serde_json::to_string_pretty(&ID_FILE).unwrap().as_bytes(),
        )
        .expect("写入/target/ser/list.josn文件出错！");
    }

    id
}
